1. (a) What is complexity of algorithm? Explain space complexity and time complexity of algorithms with the help of example. (5 marks)
Answer :
Algorithm complexity refers to the amount of computational resources that an algorithm requires. The two main types of complexity are time complexity and space complexity.
Time Complexity: This measures the amount of time an algorithm takes to complete as a function of the length of the input. It is commonly expressed using Big O notation. For example, a linear search algorithm has a time complexity of , meaning that in the worst case, it takes time proportional to the number of elements in the input list.
Space Complexity: This measures the amount of memory space an algorithm needs to run to completion. For instance, consider an algorithm that processes an array and requires an additional array of the same size to store the results. If the input array has elements, the space complexity would be .
Example:
Consider a simple algorithm that finds the maximum element in an array of integers:
function findMax(arr): max = arr[0] for i = 1 to length(arr)-1: if arr[i] > max: max = arr[i] return max
For this algorithm:
- → Time Complexity: , as it must check each element of the array once.
- → Space Complexity: , since it only uses a fixed amount of extra space regardless of the input size.